package com.stn.zjx.givingtreasure.adapter;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.came.viewbguilib.ButtonBgUi;
import com.google.gson.Gson;
import com.irozon.sneaker.Sneaker;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.activity.UserLoginActivity;
import com.stn.zjx.givingtreasure.activity.dynamic.DynamicDetailActivity;
import com.stn.zjx.givingtreasure.activity.dynamic.DynamicDetailReplyActivity;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.bean.DynamicGuest;
import com.stn.zjx.givingtreasure.bean.DynamicGuestGuest;
import com.stn.zjx.givingtreasure.domain.StatusDomain;
import com.stn.zjx.givingtreasure.event.RefreshEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.UserDynamicGuestGuestNetImpl;
import com.stn.zjx.givingtreasure.net.impl.UserDynamicGuestLikeNetImpl;
import com.stn.zjx.givingtreasure.net.impl.UserDynamicGuestNetImpl;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.table.User;
import com.stn.zjx.givingtreasure.utils.SoftInputUtils;
import com.stn.zjx.givingtreasure.utils.ToolsUtils;
import com.vondear.rxtools.RxActivityTool;
import com.zzhoujay.richtext.LinkHolder;
import com.zzhoujay.richtext.RichText;
import com.zzhoujay.richtext.callback.LinkFixCallback;
import com.zzhoujay.richtext.callback.OnUrlClickListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import me.shaohui.bottomdialog.BottomDialog;
import tv.danmaku.ijk.media.widget.media.IjkVideoView;

public class DynamicGuestAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{

   public List<DynamicGuest> dataBeanList=new ArrayList<>();
   private LayoutInflater inflater;
   public BaseActivity context;
   public DynamicGuestAdapter(BaseActivity context) {
       inflater = LayoutInflater.from(context);

      this.context=context;
   }

   @Override
   public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
       RecyclerView.ViewHolder vh = new IndexHolder(inflater.inflate(R.layout.item_dynamic_guest, parent, false));
       return vh;
   }

   @SuppressLint("SetTextI18n")
   @Override
   public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
                   IndexHolder ih= (IndexHolder) viewHolder;
       DynamicGuest       dataBean=dataBeanList.get(i);
          if(dataBean.getIsAuthor()==1){
              ih.publisher.setVisibility(View.VISIBLE);
          }else{
              ih.publisher.setVisibility(View.GONE);
          }

       Glide
               .with(context)
               .asDrawable()
                .load(dataBean.getUserAvatar())
               .apply(new RequestOptions().placeholder(R.mipmap.default_avatar))
               .transition(DrawableTransitionOptions.withCrossFade(500))
               .into(new SimpleTarget<Drawable>() {
                   @Override
                   public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                       ih.cir.setImageDrawable(resource);
                   }
               });
       ih.user_nickname.setText(dataBean.getUserNickname());
       ih.good_num.setText(String.valueOf(dataBean.getGuestlikeCount()));
       ih.content.setText(dataBean.getUserDynamicGuestContent());
     switch (dataBean.getGuestisLike()){
         case 0:
             ih.good_iv.setImageResource(R.mipmap.good_noselect);
             break;
         case 1:
             ih.good_iv.setImageResource(R.mipmap.good_select);
             break;
     }
       ih.good_bt.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               User onlineUser= UserService
                       .getInstance(context)
                       .getOnlineLoginUser();
               if(onlineUser==null){
                   RxActivityTool.skipActivity(context, UserLoginActivity.class);
                   return;
               }
               switch (dataBean.getGuestisLike()){
                   case 0:
                       ih.good_iv.setImageResource(R.mipmap.good_select);
                       ih.good_num.setText(String.valueOf(dataBean.getGuestlikeCount()+1));
                       dataBean.setGuestisLike(1);
                       dataBean.setGuestlikeCount(dataBean.getGuestlikeCount()+1);
                       set_like_dynamic_guest(onlineUser.getToken(),dataBean.getUserDynamicGuestId());
                       break;
                   case 1:
                       ih.good_iv.setImageResource(R.mipmap.good_noselect);
                       ih.good_num.setText(String.valueOf(dataBean.getGuestlikeCount()-1));
                       dataBean.setGuestisLike(0);
                       dataBean.setGuestlikeCount(dataBean.getGuestlikeCount()-1);
                       set_no_like_dynamic_guest(onlineUser.getToken(),dataBean.getUserDynamicGuestId());
                       break;
               }
           }
       });
     ih.date_time.setText(ToolsUtils.getDateBeforeAfter(dataBean.getUserDynamicGuestCreatedate()));

      switch (dataBean.getGuestGuestsCount()){
          case 0:
              ih.reply.setText(context.getString(R.string.reply));
              ih.reply.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View view) {
                      initGuestDialog(dataBean.getUserDynamicGuestId(),0,dataBean.getUserNickname());
                  }
              });
              break;
          default:
              ih.reply.setText(dataBean.getGuestGuestsCount()+context.getString(R.string.reply));
              ih.reply.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View view) {
                      Bundle bundle=new Bundle();
                       bundle.putSerializable("data",dataBean);
                     RxActivityTool.skipActivity(context, DynamicDetailReplyActivity.class,bundle);
                  }
              });
              break;
      }



      if(dataBean.getGuestGuests()!=null&&dataBean.getGuestGuests().size()!=0){
          ih.guest_guest_layout.removeAllViews();
            for(int d=0;d<dataBean.getGuestGuests().size();d++){
               DynamicGuestGuest data=dataBean.getGuestGuests().get(d);
                   TextView tv=new TextView(context);
                   LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                           LinearLayout.LayoutParams.WRAP_CONTENT);
                    lp.leftMargin=ToolsUtils.dip2px(context,10);
                    lp.rightMargin=ToolsUtils.dip2px(context,10);
                    lp.topMargin=ToolsUtils.dip2px(context,10);
                   tv.setTextSize(14f);
                   tv.setLayoutParams(lp);
                   tv.setTextColor(ActivityCompat.getColor(context,R.color.gray));
                   String htmlText="";
                     if(data.getToUserId()==0){
                         htmlText="<font color=\"#808080\" size='14'>"+data.getUserNickname()+" :  </font>"+
                          "<font color=\"#333333\" size='12'>"+data.getUserDynamicGuestGuestContent()+"</font>";
                     }else{
                         htmlText="<font color=\"#808080\" size='14'>"+data.getUserNickname()+"</font>"+
                                 "<font color=\"#333333\" size='14'> "+context.getString(R.string.reply)+" </font>"+
                                 "<font color=\"#808080\" size='14'>"+data.getToUserNickname()+" : </font>"+
                                 "<font color=\"#333333\" size='14'>"+data.getUserDynamicGuestGuestContent()+"</font>"
                         ;
                     }
                tv.setLinkTextColor(ActivityCompat.getColor(context,R.color.black));
                RichText.from(htmlText)
                        .linkFix(new LinkFixCallback() {
                            @Override
                            public void fix(LinkHolder holder) {
                                holder.setColor(ActivityCompat.getColor(context,R.color.gray));
                                holder.setUnderLine(false);
                            }
                        }).into(tv);
                ih.guest_guest_layout.addView(tv);
            }
          ih.guest_guest_layout.setVisibility(View.VISIBLE);
          ih.guest_guest_layout.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                  Bundle bundle=new Bundle();
                  bundle.putSerializable("data",dataBean);
                  RxActivityTool.skipActivity(context, DynamicDetailReplyActivity.class,bundle);
              }
          });
      }else{
          ih.guest_guest_layout.setVisibility(View.GONE);
      }


   }

   @Override
   public int getItemCount() {
       return dataBeanList.size();
   }
   public void refreshList(List<DynamicGuest> dataBeans) {
       dataBeanList.removeAll(dataBeanList);
       dataBeanList.addAll(dataBeans);
       notifyDataSetChanged();
   }

   public void appendList(List<DynamicGuest> dataBeans) {
       dataBeanList.addAll(dataBeans);
       notifyDataSetChanged();
   }

   public void clearList() {
       dataBeanList.removeAll(this.dataBeanList);
       notifyDataSetChanged();
   }
    //动态评论点赞
    public void set_like_dynamic_guest(String token, Integer userDynamicGuestId) {
        UserDynamicGuestLikeNetImpl
                .set_like_dynamic_guest(token, userDynamicGuestId, token + "_set_like_dynamic_guest_" + userDynamicGuestId, new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }
                });
    }

    //动态评论取消点赞
    public void set_no_like_dynamic_guest(String token, Integer userDynamicGuestId) {
        UserDynamicGuestLikeNetImpl
                .set_no_like_dynamic_guest(token, userDynamicGuestId, token + "_set_no_like_dynamic_guest_" + userDynamicGuestId, new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }
                });
    }

   public  class IndexHolder extends RecyclerView.ViewHolder{

             public View rootView;
         public CircleImageView cir;
         public TextView user_nickname;
         public  View good_bt;
         public ImageView good_iv;
         public TextView good_num;
         public TextView content,date_time;
         public LinearLayout guest_guest_layout;
         public TextView reply;
          public ButtonBgUi publisher;
        IndexHolder(@NonNull View itemView) {
           super(itemView);
           rootView=itemView;
            cir=itemView.findViewById(R.id.cir);
            user_nickname=itemView.findViewById(R.id.user_nickname);
            good_bt=itemView.findViewById(R.id.good_bt);
            good_iv=itemView.findViewById(R.id.good_iv);
            good_num=itemView.findViewById(R.id.good_num);
            content=itemView.findViewById(R.id.content);
            guest_guest_layout=itemView.findViewById(R.id.guest_guest_layout);
            date_time=itemView.findViewById(R.id.date_time);
            reply=itemView.findViewById(R.id.reply);
            publisher=itemView.findViewById(R.id.publisher);
        }
   }



    public void initGuestDialog(Integer userDynamicGuestId,Integer toUserId,String userNickname) {
        Dialog guest_dialog;
        EditText guest_content_edit;
        guest_dialog = new Dialog(context, R.style.dialog_soft_input);
        guest_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        guest_dialog.setContentView(R.layout.dialog_dynamic_guest_input);
        WindowManager.LayoutParams lp = guest_dialog.getWindow().getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        lp.gravity = Gravity.BOTTOM;
        guest_dialog.getWindow().setAttributes(lp);

        guest_content_edit = guest_dialog.findViewById(R.id.content_edit);
        guest_content_edit.setHint(""+context.getString(R.string.reply)+" "+userNickname);
        guest_content_edit.setHintTextColor(ActivityCompat.getColor(context,R.color.gray));
        TextView guest_num_count = guest_dialog.findViewById(R.id.num_count);
        TextView guest_send_guest_bt = guest_dialog.findViewById(R.id.send_guest_bt);
        View exit_bt = guest_dialog.findViewById(R.id.exit_bt);
        exit_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                guest_dialog.dismiss();
            }
        });
        guest_dialog.findViewById(R.id.rootView)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        guest_dialog.dismiss();
                    }
                });
        guest_content_edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                guest_num_count.setText(guest_content_edit.getText().length() + "/100");
                if (guest_content_edit.getText().length() == 0) {
                    guest_send_guest_bt.setBackgroundResource(R.drawable.focus_light_gray_5dp);
                    guest_send_guest_bt.setTextColor(ActivityCompat.getColor(context, R.color.gray));
                    guest_send_guest_bt.setClickable(false);
                } else {
                    guest_send_guest_bt.setBackgroundResource(R.drawable.focus_theme_5dp);
                    guest_send_guest_bt.setTextColor(ActivityCompat.getColor(context, R.color.white));
                    guest_send_guest_bt.setClickable(true);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        guest_send_guest_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                User onlineUser = UserService
                        .getInstance(context)
                        .getOnlineLoginUser();
                if (onlineUser == null) {
                    RxActivityTool.skipActivity(context, UserLoginActivity.class);
                    return;
                }
                send_dynamic_guest_guest(onlineUser.getToken(),
                        toUserId,
                        userDynamicGuestId,
                        guest_content_edit.getText().toString().trim(),
                        guest_dialog);

            }
        });
        guest_send_guest_bt.setClickable(false);
        guest_dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                //    guest_content_edit.getText().clear();
                // 显示软键盘
                guest_content_edit.requestFocus();
                SoftInputUtils.openSoftInput(context,guest_dialog.getCurrentFocus(),50);
                //  SoftInputUtils.showSoftInput(DynamicDetailActivity.this,guest_dialog);
            }
        });
        guest_dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {

                SoftInputUtils.closedSoftInput(context);
//                im.hideSoftInputFromWindow(guest_content_edit.getWindowToken(),0);
                guest_content_edit.getText().clear();
            }
        });
        guest_dialog.show();
    }

    //发送动态评论
    public void send_dynamic_guest_guest(String token,
                                         Integer toUserId,
                                         Integer userDynamicGuestId,
                                         String userDynamicGuestGuestContent,Dialog dialog) {
        UserDynamicGuestGuestNetImpl
                .send_dynamic_guest_guest(token, toUserId, userDynamicGuestId,
                        userDynamicGuestGuestContent,
                        token + "_send_dynamic_guest_guest_" + userDynamicGuestId,
                        new StringCallback() {
                            @Override
                            public void onStart(Request<String, ? extends Request> request) {
                                super.onStart(request);
                              context.showLoading();
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                                context. dissmissLoading();
                            }

                            @Override
                            public void onSuccess(Response<String> response) {
                                if (response.isSuccessful() && !context.isFinishing()) {
                                    StatusDomain domain = new Gson().fromJson(response.body(), StatusDomain.class);
                                    switch (domain.getStatus()) {
                                        case BaseApi.REQUEST_SUCCESS_CODE:
                                            dialog.dismiss();
                                            RefreshEvent event=new RefreshEvent();
                                            event.flag=RefreshEvent.REFRESH;
                                            EventBus.getDefault().post(event);
//                                            Sneaker.with(context)
//                                                    .autoHide(true)
//                                                    .setTitle(""+domain.getMessage(),R.color.white)
//                                                    .sneakSuccess();

                                            break;
                                       default:
//                                           Sneaker.with(context)
//                                                   .autoHide(true)
//                                                   .setTitle(""+domain.getMessage(),R.color.white)
//                                                   .sneakError();
                                           context.showToast(domain.getMessage());
                                           break;
                                    }
                                }
                            }
                        });

    }
}